<?php

declare(strict_types=1);

namespace App\CustHub\Model;

use App\Common\Constants\ErrorCode;
use App\CustHub\Service\CommonService;
use App\Enum\WordTypeEnum;
use App\Exception\BusinessException;
use Mine\MineModel;

/**
 * @property int $id
 * @property int $answer_id 问答方案id
 * @property string $title 标题
 * @property array $fuzzy_keyword
 * @property array $keyword 精准关键词
 * @property int $sort 优先级
 * @property int $status 1开启  0关闭
 * @property int $answer_type 1全部回复  2随机回复一条
 * @property \Carbon\Carbon $created_at 创建时间
 * @property \Carbon\Carbon $updated_at 更新时间
 * @property-read mixed $content 内容
 */
class ChSmartAnswerQuestion extends MineModel
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'ch_smart_answer_question';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['id', 'answer_id', 'title', 'content', 'fuzzy_keyword', 'keyword', 'sort', 'status', 'answer_type', 'created_at', 'updated_at'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['id' => 'integer', 'answer_id' => 'integer', 'content' => 'array', 'fuzzy_keyword' => 'array', 'keyword' => 'array', 'sort' => 'integer', 'status' => 'integer', 'answer_type' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    public function getContentAttribute()
    {
        return !empty($this->attributes['content'])?json_decode($this->attributes['content'],true):[];
    }

    public static function saveQuestion($data = [],$id = 0)
    {
        $model = new self();
        if($id){
            $model = self::where('id',$id) -> first();
            if(empty($model)) throw new BusinessException(ErrorCode::NOT_ISSET,'数据不存在');
        }else{
            //$model -> sort = self::query() -> max('sort') + 1;
        }
        $model -> answer_id = $data['answer_id'];
        $model -> title = $data['title'];
        if(!is_array($data['content'])){
            $data['content'] = json_decode($data['content'],true);
        }
        $info = CommonService::formatMsgContent($data['content']);
        $model -> content = $info['content'];
        $fuzzy_keyword=null;
        $keyword=null;
        !empty($data['fuzzy_keyword']) && $fuzzy_keyword = is_array($data['fuzzy_keyword'])?$data['fuzzy_keyword']:json_decode($data['fuzzy_keyword'],true);
        !empty($data['keyword']) && $keyword = is_array($data['keyword'])?$data['keyword']:json_decode($data['keyword'],true);
        $model -> fuzzy_keyword = $fuzzy_keyword;
        $model -> keyword = $keyword;

        $model -> sort = $data['sort'];
        $model -> answer_type = $data['answer_type'];
        $model -> save();
        return $model;
    }

}
